import requests
import json
from flask import Flask, request,jsonify
import logging
import pymysql.cursors
import uuid
import system_setup
from datetime import datetime
from configparser import ConfigParser
from uirls import mqtt_client
# 读取配置文件
conf = ConfigParser()
conf.read("setting.ini",encoding='utf-8')
server = Flask(__name__)
# log日志
logging.basicConfig(level = logging.DEBUG,format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s')


# 数据库连接
def mysql():
    mydb = pymysql.connect(
        host=conf.get("mysql_settings","host"),
        port=int(conf.get("mysql_settings","port")),
        user=conf.get("mysql_settings","user"),
        password=conf.get("mysql_settings","password"),
        database='data_info',
        cursorclass=pymysql.cursors.DictCursor
    )
    return mydb


# 数据订阅
def data(jsonParam):
    # 原始数据
    # jsonParam = json.loads(request.data)
    mydb = mysql()
    mydb.connect()
    cursor = mydb.cursor()
    sql = "SELECT * from subscription_address where state = 1 and type = 1"
    cursor.execute(sql)
    cur_data = cursor.fetchall()
    headers = {
        "Content-Type": "application/json; charset=UTF-8"
    }
    for item in cur_data:
        response = requests.post(item['url'], data=json.dumps(jsonParam), headers=headers,timeout=5).text
        logging.debug("response:%s"%response)
    cursor.close()
    mydb.close()
    return jsonify(code=0,msg="success")


# mqtt数据订阅
def mqtt_data(jsonParam):

    mydb = mysql()
    mydb.connect()
    cursor = mydb.cursor()
    sql = "SELECT * from subscription_address where state = 1 and type = 2"
    cursor.execute(sql)
    cur_data = cursor.fetchall()
    for item in cur_data:
        mqtt_client.mqtt_client(item['mqtt_add'],int(item['mqtt_port']),item['mqtt_topic'],jsonParam)
    cursor.close()
    mydb.close()
    return jsonify(code=0,msg="success")


# 短信、语音通知
def dataPush(jsonParam):
    # 原始数据
    # jsonParam = json.loads(request.data)
    mydb = mysql()
    mydb.connect()
    cursor = mydb.cursor()
    sql = "SELECT * from device_info.communication"
    cursor.execute(sql)
    cur_data = cursor.fetchall()
    headers = {
        "Content-Type": "application/json; charset=UTF-8"
    }
    # 短信、语音地址
    url = "http://127.0.0.1:8107/alarmInfo/communicate"
    for item in cur_data:
        jsonParam['phone'] = item['phone']
        if item['type'] == 1:
            jsonParam['type'] = item['1']
            response = requests.post(url, data=json.dumps(jsonParam), headers=headers,timeout=5).text
            # 添加通知记录
            communication_record_add(jsonParam)
            logging.debug("response:%s"%response)
        else:
            jsonParam['type'] = item['2']
            response = requests.post(url, data=json.dumps(jsonParam), headers=headers,timeout=5).text
            # 添加通知记录
            communication_record_add(jsonParam)
            logging.debug("response:%s"%response)
    cursor.close()
    mydb.close()
    return jsonify(code=0,msg="success")


# 调试短信、语音通知
def data_push_test():
    response = system_setup.getDecodeToken(request.headers.get("Authorization","")[7:])
    token = json.loads(response.data)
    if token['code'] == 1:
        return jsonify(
            msg=token['msg'],
            code=1
        )
    elif token['code'] == 401:
        return jsonify(
            msg=token['msg'],
            code=token['code']
        )
    jsonParam = {}
    jsonParam['name'] = "调试"
    jsonParam['position'] = "调试位置"
    jsonParam['content'] = "调试预警"
    jsonParam['alarmTypeName'] = "调试预警"
    jsonParam['number'] = "调试"
    headers = {
        "Content-Type": "application/json; charset=UTF-8"
    }
    # 短信、语音地址
    url = "http://127.0.0.1:8107/alarmInfo/communicate"
    try:
        jsons = request.json
        if jsons.__contains__('phone') and jsons.__contains__('type'):
            jsonParam['phone'] = jsons['phone']
            if jsons['type'] == 1:
                jsonParam['type'] = jsons['type']
                response = requests.post(url, data=json.dumps(jsonParam), headers=headers,timeout=5).text
                # 添加通知记录
                communication_record_add(jsonParam)
                logging.debug("response:%s"%response)
            else:
                jsonParam['type'] = jsons['type']
                response = requests.post(url, data=json.dumps(jsonParam), headers=headers,timeout=5).text
                # 添加通知记录
                communication_record_add(jsonParam)
                logging.debug("response:%s"%response)
        else:
            return jsonify(code=1,msg="缺少必要参数phone,type")
    except Exception as e:
        print(e)
        return jsonify(
            code=1,
            msg="Server internal error"
        )
    return jsonify(
        msg="success",
        code=0
    )


# 通知记录新增
def communication_record_add(jsonParam):
    id = str(uuid.uuid4())
    phone = jsonParam['phone']
    number = jsonParam['number']
    type = jsonParam['type']
    time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    mydb = mysql()
    mydb.connect()
    cursor = mydb.cursor()
    #新增订阅地址
    sql = "insert into device_info.communication_record (id,phone,number,type,time) values('%s','%s','%s',%s,'%s')"%(id,phone,number,type,time)
    cursor.execute(sql)
    mydb.commit()
    cursor.close()
    mydb.close()


# 订阅地址新增
def setSubscriptionAddress():
    response = system_setup.getDecodeToken(request.headers.get("Authorization","")[7:])
    token = json.loads(response.data)
    if token['code'] == 1:
        return jsonify(
            msg=token['msg'],
            code=1
        )
    elif token['code'] == 401:
        return jsonify(
            msg=token['msg'],
            code=token['code']
        )
    mydb = mysql()
    mydb.connect()
    cursor = mydb.cursor()
    try:
        jsons = request.json
        if jsons.__contains__('name'):
            id = str(uuid.uuid4())
            type = jsons.get('type')
            if type is None:return jsonify(code=1,msg="type 不能为null")
            url = ''
            mqtt_add = ''
            mqtt_port = ''
            mqtt_topic = ''
            # 1 http 2 mqtt
            if type == 1:
                url = jsons.get('url')
                if url is None:return jsonify(code=1,msg="url 不能为null")
                #删除原来的订阅地址
                sql = "DELETE FROM subscription_address WHERE url = '" + url + "'"
                cursor.execute(sql)
                mydb.commit()
            else:
                mqtt_add = jsons.get('mqtt_add')
                if mqtt_add is None:return jsonify(code=1,msg="mqtt_add 不能为null")
                mqtt_port = jsons.get('mqtt_port')
                if mqtt_port is None:return jsonify(code=1,msg="mqtt_port 不能为null")
                mqtt_topic = jsons.get('mqtt_topic')
                if mqtt_topic is None:return jsonify(code=1,msg="mqtt_topic 不能为null")
            name = jsons.get('name')
            if name is None:return jsonify(code=1,msg="name 不能为null")
            remark = ''
            if jsons.__contains__('remark'):remark = jsons['remark']

            #新增订阅地址
            sql = "insert into subscription_address (id,name,url,remark,type,mqtt_add,mqtt_port,mqtt_topic) values('%s','%s','%s','%s','%s','%s','%s','%s')"%(id,name,url,remark,type,mqtt_add,mqtt_port,mqtt_topic)
            cursor.execute(sql)
            mydb.commit()
        else:
            return jsonify(code=1,msg="缺少必要参数name")
    except Exception as e:
        return jsonify(code=1,msg="errr---%s"%e)
    finally:
        cursor.close()  # 关闭游标
        mydb.close()
    return jsonify(code=0,msg="success")


# 订阅地址删除
def delSubscriptionAddress():
    response = system_setup.getDecodeToken(request.headers.get("Authorization","")[7:])
    token = json.loads(response.data)
    if token['code'] == 1:
        return jsonify(
            msg=token['msg'],
            code=1
        )
    elif token['code'] == 401:
        return jsonify(
            msg=token['msg'],
            code=token['code']
        )
    mydb = mysql()
    mydb.connect()
    cursor = mydb.cursor()
    try:
        jsons = request.json
        if jsons.__contains__('id'):
            id = jsons.get('id')
            if id is None:return jsonify(code=1,msg="id 不能为null")
            sql = "DELETE FROM subscription_address WHERE id = '" + id + "'"
            cursor.execute(sql)
            mydb.commit()
        else:
            return jsonify(code=1,msg="缺少必要参数id")
    except Exception as e:
        return jsonify(code=1,msg="errr---%s"%e)
    finally:
        cursor.close()  # 关闭游标
        mydb.close()
    return jsonify(code=0,msg="success")


# 更新订阅地址状态
def updateSubscriptionAddressState():
    response = system_setup.getDecodeToken(request.headers.get("Authorization","")[7:])
    token = json.loads(response.data)
    if token['code'] == 1:
        return jsonify(
            msg=token['msg'],
            code=1
        )
    elif token['code'] == 401:
        return jsonify(
            msg=token['msg'],
            code=token['code']
        )
    mydb = mysql()
    mydb.connect()
    cursor = mydb.cursor()
    try:
        jsons = request.json
        if jsons.__contains__('state') and jsons.__contains__('id'):
            id = jsons['id']
            state = jsons['state']
            sql = "UPDATE subscription_address SET state = '%s' where id = '%s'" %(state,id)
            cursor.execute(sql)
            mydb.commit()
        else:
            return jsonify(code=1,msg="缺少必要参数id、state")
    except Exception as e:
        print(e)
        return jsonify(
            code=1,
            msg="Server internal error"
        )
    finally:
        cursor.close()  # 关闭游标
        mydb.close()  # 再关闭数据库连接
    return jsonify(
        msg="success",
        code=0
    )


# 订阅地址列表
def subscriptionAddressList():
    response = system_setup.getDecodeToken(request.headers.get("Authorization","")[7:])
    token = json.loads(response.data)
    if token['code'] == 1:
        return jsonify(
            msg=token['msg'],
            code=1
        )
    elif token['code'] == 401:
        return jsonify(
            msg=token['msg'],
            code=token['code']
        )
    mydb = mysql()
    mydb.connect()
    cursor = mydb.cursor()
    try:
        jsons = request.args
        sql = "SELECT * from subscription_address"
        cursor.execute(sql)
        cur_data = cursor.fetchall()
    except Exception as e:
        print(e)
        return jsonify(
            code=1,
            msg="Server internal error"
        )
    finally:
        cursor.close()  # 关闭游标
        mydb.close()  # 再关闭数据库连接
    return jsonify(
        msg="success",
        code=0,
        data=cur_data
    )
